package com.ruoyi.framework.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 新增或更新时自动填充公共字段处理器
 * @author liping
 */
@Slf4j
@Component
public class CreateAndUpdateHandler implements MetaObjectHandler {

    /**
     * 新增时自动填充公共字段(创建者,创建时间,更新者,更新时间)
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        String userName = currentUserName();
        strictInsertFill(metaObject, "createBy", String.class, userName);
        strictInsertFill(metaObject, "createTime", Date.class, now);
        strictInsertFill(metaObject, "updateBy", String.class, userName);
        strictInsertFill(metaObject, "updateTime", Date.class, now);
        //创建人不为空
        if(metaObject.findProperty("createById",true)!=null){
            strictInsertFill(metaObject, "createById", Long.class,currentUserId());
        }
    }

    /**
     * 更新时自动填充公共字段(更新者,更新时间)
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = new Date();
        String userName = currentUserName();
        setFieldValByName("updateBy", userName, metaObject);
        setFieldValByName("updateTime", now, metaObject);
    }

    /**
     * 获取当前登录账号
     * @return
     */
    private String currentUserName(){
        try{
            return SecurityUtils.getUsername();
        }catch (Exception e){
            log.warn("自动注入警告 => 用户未登录");
        }
        return null;
    }

    private Long currentUserId(){
        try{
            return SecurityUtils.getUserId();
        }catch (Exception e){
            log.warn("自动注入警告 => 用户未登录");
        }
        return null;
    }

}
